<template>
  <div class="app-container">
    <!-- 上半部分：搜索和入库单表格 -->
    <div class="top-section">
      <!-- 搜索表单 -->
      <el-form :inline="true" :model="queryParams" class="search-form" size="small">
        <el-form-item label="入库单编号">
          <el-input v-model="queryParams.recpt_code" placeholder="请输入入库单编号" clearable />
        </el-form-item>
        <el-form-item label="入库单名称">
          <el-input v-model="queryParams.recpt_name" placeholder="请输入入库单名称" clearable />
        </el-form-item>
        <el-form-item label="采购订单名称" v-if="queryParams.storage_type === '1'">
          <el-input v-model="queryParams.po_name" placeholder="请输入采购订单名称" clearable />
        </el-form-item>
        <el-form-item label="供应商名称" v-if="queryParams.storage_type === '1'">
          <el-input v-model="queryParams.supplier_name" placeholder="请输入供应商名称" clearable />
        </el-form-item>
        <el-form-item label="入库单状态">
          <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
            <el-option label="待提交" value="1" />
            <el-option label="待质检" value="2" />
            <el-option label="合格" value="3" />
            <el-option label="不合格" value="4" />
            <el-option label="部分合格" value="5" />
            <el-option label="已入库" value="6" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 操作按钮 -->
      <div class="operation-buttons">
        <div class="left-buttons">
          <el-button type="primary" plain @click="handleAdd" v-if="queryParams.storage_type === '1'">
            <i class="el-icon-plus"></i> 新增入库单
          </el-button>
          <el-button type="danger" plain :disabled="!deletableRows.length" @click="handleBatchDelete">
            <i class="el-icon-delete"></i> 批量删除
          </el-button>
        </div>
        <div class="top-right-btn">
          <el-button icon="el-icon-refresh" circle @click="getList" />
        </div>
      </div>

      <!-- 入库单表格 -->
      <el-table
        v-loading="loading"
        :data="receiptList"
        @selection-change="handleSelectionChange"
        highlight-current-row
        style="width: 100%"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column prop="recpt_code" label="入库单编号" align="center" show-overflow-tooltip>
          <template slot-scope="scope">
            <el-link type="primary" :underline="false" @click="handleViewDetail(scope.row)">
              {{ scope.row.recpt_code }}
            </el-link>
          </template>
        </el-table-column>
        <el-table-column prop="recpt_name" label="入库单名称" align="center" show-overflow-tooltip />
        <el-table-column prop="po_code" label="采购订单编号" align="center" show-overflow-tooltip v-if="queryParams.storage_type === '1'" />
        <el-table-column prop="supplier_name" label="供应商名称" align="center" show-overflow-tooltip v-if="queryParams.storage_type === '1'" />
        <el-table-column prop="warehouse_name" label="仓库名称" align="center" show-overflow-tooltip />
        <el-table-column prop="batch_code" label="批次编号" align="center" show-overflow-tooltip />
        <el-table-column prop="recpt_date" label="入库日期" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.recpt_date">{{ formatDateTime(scope.row.recpt_date) }}</span>
            <span v-else>待入库</span>
          </template>
        </el-table-column>
        <!-- 已移除入库数量列 -->
        <el-table-column prop="status" label="状态" align="center">
          <template slot-scope="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="create_time" label="创建时间" align="center">
          <template slot-scope="scope">
            {{ formatDateTime(scope.row.create_time) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="220">
          <template slot-scope="{ row }">
            <template v-if="row.status === '1'">
              <el-button type="text" @click="handleEdit(row)">
                <i class="el-icon-edit"></i> 编辑
              </el-button>
              <el-button type="text" @click="handleSingleItemDelete(row)">
                <i class="el-icon-delete"></i> 删除
              </el-button>
              <el-button type="text" @click="handleSubmit(row)">
                <i class="el-icon-check"></i> 提交
              </el-button>
            </template>
            <template v-else-if="row.status === '3' || row.status === '5'">
              <el-button type="text" @click="handleWarehouse(row)">
                <i class="el-icon-shopping-cart-full"></i> 入库
              </el-button>
            </template>
            <template v-else-if="row.status === '4'">
              <el-button type="text" @click="handleReturn(row)">
                <i class="el-icon-back"></i> 退货
              </el-button>
            </template>
            <template v-else-if="row.status === '6'">
              <span>---</span>
            </template>
            <template v-else>
              <span>---</span>
            </template>
          </template>
        </el-table-column>
      </el-table>

      <!-- 入库单分页 -->
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>

    <!-- 入库商品详情对话框 -->
    <el-dialog :title="`入库单详情 - ${currentReceipt.recpt_code || ''}`" :visible.sync="detailDialogVisible" width="1200px" append-to-body>
      <div v-if="currentReceipt.recpt_id" class="receipt-info">
        <div class="info-section">
          <el-descriptions :column="3" border>
            <el-descriptions-item label="入库单名称">{{ currentReceipt.recpt_name }}</el-descriptions-item>
            <el-descriptions-item label="采购订单编号">{{ currentReceipt.po_code }}</el-descriptions-item>
            <el-descriptions-item label="供应商">{{ currentReceipt.supplier_name }}</el-descriptions-item>
            <el-descriptions-item label="仓库">{{ currentReceipt.warehouse_name }}</el-descriptions-item>
            <el-descriptions-item label="批次编号">{{ currentReceipt.batch_code }}</el-descriptions-item>
            <el-descriptions-item label="状态">
              <el-tag :type="getStatusType(currentReceipt.status)">
                {{ getStatusText(currentReceipt.status) }}
              </el-tag>
            </el-descriptions-item>
          </el-descriptions>
        </div>

        <div class="table-section" style="margin-top: 20px;">
          <div class="section-title">入库商品明细</div>
          <el-table
            :data="receiptItems"
            style="width: 100%"
            border
            v-loading="detailLoading"
          >
            <el-table-column prop="goods_code" label="物料编号" align="center" width="160" />
            <el-table-column prop="goods_name" label="物料名称" align="center" />
            <el-table-column prop="stock_sfn" label="规格型号" align="center" width="180" />
            <el-table-column prop="unit_name" label="单位" align="center" width="80" />
            <el-table-column prop="recived_num" label="入库数量" align="center" width="120" />
            <el-table-column prop="status" label="质检状态" align="center" width="120">
              <template slot-scope="scope">
                <el-tag :type="getQcStatusType(scope.row.status)">
                  {{ getQcStatusText(scope.row.status) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="location_name" label="库区" align="center" width="120" />
            <el-table-column prop="area_name" label="库位" align="center" width="120" />
            <el-table-column label="操作" align="center" width="120">
              <template slot-scope="scope">
                <template v-if="currentReceipt.status !== '1' && currentReceipt.status !== '2'">
                   <el-button type="text" @click="handleViewQcReport(scope.row)">查看质检单</el-button>
                </template>
                <template v-else>
                  ---
                </template>
              </template>
            </el-table-column>
          </el-table>
          <pagination
            v-show="detailTotal > 0"
            :total="detailTotal"
            :page.sync="detailPageNum"
            :limit.sync="detailPageSize"
            @pagination="handleDetailPageChange"
          />
        </div>

        <div class="remarks" style="margin-top: 20px;" v-if="currentReceipt.remark">
          <div class="section-title">备注信息</div>
          <el-input type="textarea" v-model="currentReceipt.remark" :rows="3" readonly />
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import Pagination from "@/components/Pagination"
import {
  listItemReceipts,
  batchDeleteItemReceipts,
  warehouseItemReceipt,
  returnItemReceipt,
  recptStore,
  getItemReceiptDetail,
  submitReceipt
} from "@/views/ck/js/receipt"

export default {
  name: 'ItemReceipt',
  components: {
    Pagination
  },
  data() {
    return {
      loading: false,
      selectedRows: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        recpt_code: undefined,
        recpt_name: undefined,
        po_name: undefined,
        storage_type: undefined,
        supplier_name: undefined,
        status: undefined
      },
      receiptList: [],
      total: 0,
      detailDialogVisible: false,
      currentReceipt: {},
      receiptItems: [],
      detailLoading: false,
      detailPageNum: 1,
      detailPageSize: 10,
      detailTotal: 0
    }
  },
  computed: {
    // 计算属性：获取可删除的入库单（待提交状态）
    deletableRows() {
      return this.selectedRows.filter(row => row.status === '1');
    }
  },
  created() {
    this.queryParams.storage_type = this.$route.meta.storage_type; // 获取入库类型
    this.getList()
  },
  methods: {
    getList() {
      this.loading = true
      listItemReceipts(this.queryParams).then(response => {
        this.receiptList = response.rows || []
        this.total = response.total || 0
        this.loading = false
      }).catch(error => {
        console.error('获取入库单列表失败:', error)
        this.loading = false
        this.$message.error('获取数据失败')
      })
    },
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        recpt_code: undefined,
        recpt_name: undefined,
        po_name: undefined,
        storage_type: undefined,
        supplier_name: undefined,
        status: undefined
      }
      this.queryParams.storage_type = this.$route.meta.storage_type; // 获取入库类型
      this.getList()
    },
    handleSelectionChange(selection) {
      this.selectedRows = selection
    },
    handleAdd() {
      this.$router.push('/ck/PurchaseInventory/addReceipt')
    },
    handleEdit(row) {
      // 跳转到新增页面，带上当前点击订单
      this.$router.push({
        path: '/ck/PurchaseInventory/updateReceipt',
        query: { order: JSON.stringify(row) }
      })
    },
    handleViewDetail(row) {
      this.currentReceipt = row;
      this.detailPageNum = 1; // 重置分页
      this.getReceiptItems();
      this.detailDialogVisible = true;
    },
    getReceiptItems() {
      this.detailLoading = true;
      const params = {
        pageNum: this.detailPageNum,
        pageSize: this.detailPageSize
      };
      getItemReceiptDetail(this.currentReceipt.recpt_id, params).then(response => {
        this.receiptItems = response.rows || [];
        this.detailTotal = response.total || 0;
        this.detailLoading = false;
      }).catch(error => {
        console.error('获取入库单详情失败:', error);
        this.detailLoading = false;
        this.$message.error('获取入库单详情失败');
      });
    },
    handleDetailPageChange() {
      this.getReceiptItems();
    },

    handleSingleItemDelete(row) {
      this.$confirm(`确认删除入库单"${row.recpt_name}"吗？<br/><br/><span style="color: #E6A23C; font-weight: bold;">注意：删除入库单的同时，订单下的所有入库商品详情也将被一并删除！</span>`, '删除确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        dangerouslyUseHTMLString: true
      }).then(() => {
        this.batchDeleteItemReceipts([row.recpt_id]);
      }).catch(() => {});
    },

    // 批量删除方法
    handleBatchDelete() {
      const deletableRows = this.deletableRows;
      if (deletableRows.length === 0) {
        this.$message.warning('请选择状态为"待提交"的入库单进行删除');
        return;
      }

      // 计算选中的总记录和可删除记录的数量
      const totalSelected = this.selectedRows.length;
      const deletableCount = deletableRows.length;

      // 获取要删除的入库单名称列表
      const receiptNames = deletableRows.map(row => row.recpt_name);
      // 如果入库单数量多于3个，只显示前3个，其余用"等"表示
      const displayNames = receiptNames.length > 3
        ? receiptNames.slice(0, 3).join('、') + `等${receiptNames.length}个入库单`
        : receiptNames.join('、');

      let confirmMessage = `确认删除以下入库单吗？<br/><br/>${displayNames}`;

      // 如果选中的记录中有不是可删除状态的，添加提示信息
      if (totalSelected > deletableCount) {
        confirmMessage += `<br/><br/><span style="color: #E6A23C;">注意：您选择了${totalSelected}个入库单，但只有${deletableCount}个（状态为“待提交”）将被删除。</span>`;
      }

      // 添加关于删除入库商品详情的警告
      confirmMessage += `<br/><br/><span style="color: #E6A23C; font-weight: bold;">注意：删除入库单的同时，订单下的所有入库商品详情也将被一并删除！</span>`;

      this.$confirm(confirmMessage, '删除确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        dangerouslyUseHTMLString: true
      }).then(() => {
        // 提取所有待删除入库单的ID
        const recptIds = deletableRows.map(row => row.recpt_id);
        this.batchDeleteItemReceipts(recptIds);
      }).catch(() => {});
    },

    // 批量删除入库单的API调用
    batchDeleteItemReceipts(recptIds) {
      this.loading = true;
      batchDeleteItemReceipts(recptIds).then(response => {
        this.loading = false;
        if (response.code === 200) {
          this.$message.success('删除成功');
          this.getList();
        } else {
          this.$message.error(response.msg || '删除失败');
        }
      }).catch(error => {
        this.loading = false;
        console.error('删除入库单失败:', error);
        this.$message.error('删除失败');
      });
    },

    // 提交入库单
    handleSubmit(row) {
      this.$confirm(`确认提交入库单"${row.recpt_name}"吗？`, '提交确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const loading = this.$loading({
          lock: true,
          text: '正在提交入库单，请稍候...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });

        submitReceipt(row.recpt_id).then(response => {
          loading.close();
          if (response.code === 200) {
            this.$message.success('入库单提交成功');
            this.getList(); // 刷新列表
          } else {
            this.$message.error(response.msg || '入库单提交失败');
          }
        }).catch(error => {
          loading.close();
          console.error('提交入库单失败:', error);
          this.$message.error('提交入库单失败，请稍后重试');
        });
      }).catch(() => {});
    },

    // 退货操作
    handleReturn(row) {
      this.$confirm(`确认将入库单"${row.recpt_name}"中的物料退货吗？`, '退货确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const loading = this.$loading({
          lock: true,
          text: '正在处理退货操作，请稍候...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });

        // 调用退货API
        returnItemReceipt(row.recpt_id).then(response => {
          loading.close();
          if (response.code === 200) {
            this.$message.success('物料退货成功');
            this.getList(); // 刷新列表
          } else {
            this.$message.error(response.msg || '物料退货失败');
          }
        }).catch(error => {
          loading.close();
          console.error('物料退货失败:', error);
          this.$message.error('物料退货失败，请稍后重试');
        });
      }).catch(() => {});
    },

    // 入库操作
    handleWarehouse(row) {
      this.$confirm(`确认将入库单"${row.recpt_name}"中的物料入库吗？`, '入库确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const loading = this.$loading({
          lock: true,
          text: '正在处理入库操作，请稍候...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });

        row.update_by = this.$store.getters.name; // 更新人
        // 调用入库API
        recptStore(row).then(response => {
          loading.close();
          if (response.code === 200) {
            this.$message.success('物料入库成功');
            this.getList(); // 刷新列表
          } else {
            this.$message.error(response.msg || '物料入库失败');
          }
        }).catch(error => {
          loading.close();
          console.error('物料入库失败:', error);
          this.$message.error('物料入库失败，请稍后重试');
        });
      }).catch(() => {});
    },

    formatDateTime(date) {
      if (!date) return '';
      const d = new Date(date);
      const year = d.getFullYear();
      const month = (d.getMonth() + 1).toString().padStart(2, '0');
      const day = d.getDate().toString().padStart(2, '0');
      const hours = d.getHours().toString().padStart(2, '0');
      const minutes = d.getMinutes().toString().padStart(2, '0');
      const seconds = d.getSeconds().toString().padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },

    getStatusType(status) {
      const statusMap = {
        '1': 'info',     // 待提交
        '2': 'warning',  // 待质检
        '3': 'success',  // 合格
        '4': 'danger',  // 不合格
        '5': 'warning',    // 部分合格
        '6': 'primary'    // 已入库
      }
      return statusMap[status] || 'info'
    },

    getStatusText(status) {
      const statusMap = {
        '1': '待提交',
        '2': '待质检',
        '3': '合格',
        '4': '不合格',
        '5': '部分合格',
        '6': '已入库'
      }
      return statusMap[status] || '未知'
    },

    getQcStatusType(status) {
      const statusMap = {
        '1': 'warning',  // 待质检
        '2': 'success',  // 合格
        '3': 'danger'   // 不合格
      };
      return statusMap[status] || 'info';
    },

    getQcStatusText(status) {
      const statusMap = {
        '1': '待质检',
        '2': '合格',
        '3': '不合格'
      };
      return statusMap[status] || '未知';
    },

    formatNumber(num) {
      if (num === null || num === undefined) return '0';
      return num.toLocaleString();
    },

    formatCurrency(amount) {
      if (amount === null || amount === undefined) return '0.00';
      return amount.toFixed(2);
    },

    // 查看质检单（占位）
    handleViewQcReport(row) {
      // 后续可在此处实现跳转或弹窗显示质检单详情
      this.$router.push(`/qc/IncomingInspection/detail/${row.iqc_id}`);
    }
  }
}
</script>

<style scoped>
.app-container {
  padding: 20px;
  width: 100%;
  box-sizing: border-box;
}

.top-section {
  margin-bottom: 30px;
  width: 100%;
}

.search-form {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 4px;
  width: 100%;
  box-sizing: border-box;
}

.operation-buttons {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.left-buttons {
  display: flex;
  gap: 5px;
}

.top-right-btn {
  display: flex;
  gap: 10px;
}

.el-table {
  margin-bottom: 20px;
  width: 100% !important;
}

.el-table th {
  background-color: #f5f7fa;
}

/* 确保表格容器也是100%宽度 */
.el-table__body-wrapper {
  width: 100%;
}

.el-table__header-wrapper {
  width: 100%;
}

/* 操作列紧贴右边界 */
.el-table .el-table__cell:last-child {
  padding-right: 0 !important;
}

.el-table .el-table__cell:last-child .cell {
  padding-right: 10px !important;
}

/* 商品详情对话框样式 */
.receipt-info {
  padding: 10px;
}

.section-title {
  font-weight: bold;
  font-size: 16px;
  margin-bottom: 10px;
  color: #303133;
  border-left: 4px solid #409EFF;
  padding-left: 10px;
}

.info-section {
  margin-bottom: 20px;
}

/* 确保对话框内的表格正常显示 */
.receipt-info .el-table {
  width: 100% !important;
}

.el-table-column {
  text-align: center;
}
</style>
